<template>
  <div class="ai-chat">
    <!-- 头部标题 -->
    <div class="chat-header">
      <div class="header-content">
        <button class="back-button" @click="goBack">
          <svg width="20" height="20" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
            <path d="M19 12H5M12 19l-7-7 7-7" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
          </svg>
        </button>
        <div class="title-section">
          <h1 class="chat-title">求职智能问答</h1>
        </div>
        
      </div>
    </div>

    <!-- 聊天区域 -->
    <div class="chat-container">
             <!-- 聊天会话列表 -->
       <div class="chat-sidebar">
         <div class="sidebar-header">
           <h3>聊天会话</h3>
           <div class="header-actions">
             <button class="new-chat-btn" @click="createNewSession" title="新建会话">
               <svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                 <path d="M12 5v14M5 12h14" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
               </svg>
             </button>
            
            </div>
         </div>
         <div class="history-list" ref="historyList">
           <div v-if="chatSessions.length === 0" class="no-history">
             <p>暂无聊天会话</p>
           </div>
           <div 
             v-for="session in chatSessions" 
             :key="session.sessionId" 
             class="history-item"
             :class="{ active: selectedSessionId === session.sessionId }"
             @click="selectSession(session)"
           >
             <div class="history-content">
               <div class="history-question">{{ session.sessionTitle }}</div>
                <div class="session-info">
                  <span class="history-time">{{ formatTime(session.lastActiveTime) }}</span>
                </div>
                <button
        class="floating-delete-btn"
        :disabled="!selectedSessionId"
        title="删除当前会话"
        @click="selectedSessionId && deleteSession(selectedSessionId)"
      >
        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
          <path d="M3 6h18M8 6V4a2 2 0 012-2h4a2 2 0 012 2v2m3 0v14a2 2 0 01-2 2H7a2 2 0 01-2-2V6h14z" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
        </svg>
      </button>
             </div>
           </div>
         </div>
       </div>

      <!-- 主聊天区域 -->
      <div class="main-chat-area">
      <!-- 消息列表 -->
      <div class="messages-container" ref="messagesContainer">
        <div v-if="messages.length === 0" class="welcome-message">
          <div class="welcome-content">
            <h2>欢迎使用求职智能问答</h2>
            <p>我可以帮助您：</p>
            <ul>
              <li>解答编程技术问题</li>
              <li>提供代码示例和解释</li>
              <li>协助求职面试准备</li>
              <li>分享编程学习建议</li>
              <li>职业规划指导</li>
            </ul>
            <p>请随时向我提问吧！</p>
          </div>
        </div>

        <!-- 历史消息 -->
        <ChatMessage
          v-for="message in messages"
          :key="message.id"
          :message="message.content"
          :is-user="message.isUser"
          :timestamp="message.timestamp"
        />

        <!-- AI 正在回复的消息 -->
        <div v-if="isAiTyping" class="chat-message ai-message">
          <div class="message-avatar">
            <div class="avatar ai-avatar">AI</div>
          </div>
          <div class="message-content">
            <div class="message-bubble">
              <div class="ai-typing-content">
                <div class="ai-response-text message-markdown" v-html="currentAiResponseRendered"></div>
                <LoadingDots v-if="isStreaming" />
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 输入框 -->
      <ChatInput
        :disabled="isAiTyping"
        @send-message="sendMessage"
        placeholder="请输入您的编程问题..."
      />
      </div>
    </div>
  </div>
</template>

<script>
import ChatMessage from '@/components/ChatMessage.vue'
import ChatInput from '@/components/ChatInput.vue'
import LoadingDots from '@/components/LoadingDots.vue'
import { chatWithSSE, saveAiTalks, clearAiTalks, getChatHistory, getChatSessions, getSessionMessages, createChatSession, deleteChatSession } from '@/api/aiChatApi.js'
import { isLoggedIn } from '@/utils/auth.js'
import { marked } from 'marked'

export default {
  name: 'AiChat',
  components: {
    ChatMessage,
    ChatInput,
    LoadingDots
  },
  data() {
    return {
      messages: [],
      isAiTyping: false,
      isStreaming: false,
      currentAiResponse: '',
      currentEventSource: null,
      connectionError: false,
      isLoggedIn: false,
      chatSessions: [],
      selectedSessionId: null,
      isLoadingSessions: false,
      currentSession: null
    }
  },
  computed: {
    currentAiResponseRendered() {
      if (!this.currentAiResponse || this.currentAiResponse.trim() === '') return ''
      try {
      // 配置marked选项
      marked.setOptions({
        breaks: true, // 支持换行
        gfm: true, // 支持GitHub风格的Markdown
        sanitize: false, // 不过滤HTML（根据需要可以开启）
        highlight: function(code, lang) {
          return code
        }
      })
      return marked(this.currentAiResponse)
      } catch (error) {
        console.error('Markdown渲染错误:', error)
        return this.currentAiResponse || ''
      }
    }
  },
  mounted() {
    // 检查登录状态并加载数据
    this.checkLoginStatus()
  },
  methods: {
    checkLoginStatus() {
      this.isLoggedIn = isLoggedIn()
      if (!this.isLoggedIn) {
        this.connectionError = true
        console.warn('用户未登录，无法使用AI对话功能')
      } else {
        // 登录后加载会话列表
        this.loadChatSessions()
      }
    },
    
    sendMessage(message) {
      // 检查登录状态
      if (!this.isLoggedIn) {
        this.connectionError = true
        return
      }
      
      // 防重复提交：检查是否正在处理中
      if (this.isAiTyping) {
        console.warn('AI正在回复中，请稍后再试')
        return
      }
      
      // 防重复提交：检查是否与上一条消息相同
      if (this.messages.length > 0) {
        const lastMessage = this.messages[this.messages.length - 1]
        if (lastMessage.isUser && lastMessage.content === message) {
          console.warn('消息重复，请勿重复发送')
          return
        }
      }
      
      // 添加用户消息
      this.addMessage(message, true)
      
      // 开始AI回复
      this.startAiResponse(message)
      
      // 不再在前端冗余保存历史（后端已在对话过程中持久化）
    },
    
    addMessage(content, isUser = false) {
      // 确保内容不为空
      if (!content || content.trim() === '') {
        console.warn('尝试添加空消息:', { content, isUser })
        return
      }
      
      const message = {
        id: Date.now() + Math.random(),
        content: content.trim(),
        isUser,
        timestamp: new Date() // 确保是Date类型
      }
      this.messages.push(message)
      this.scrollToBottom()
    },
    
    // 开始AI回复
    async startAiResponse(message) {
      if (!this.selectedSessionId) {
        console.error('未选择会话，无法发送消息')
        return
      }
      
      this.isAiTyping = true
      this.currentAiResponse = ''
      this.isStreaming = true
      
      try {
        // 使用SSE进行流式对话（使用正确的回调签名）
        const eventSource = await chatWithSSE(
          message,
          // onMessage
          (chunk) => {
            this.currentAiResponse += chunk
            this.scrollToBottom()
          },
          // onError
          (error) => {
            console.error('SSE连接错误:', error)
            this.isAiTyping = false
            this.isStreaming = false
          },
          // onClose
          () => {
            // AI回复完成后，刷新消息与会话
            this.isAiTyping = false
            this.isStreaming = false
            this.loadSessionMessages(this.selectedSessionId)
            this.loadChatSessions()
          },
          // sessionId
          this.selectedSessionId
        )
        this.currentEventSource = eventSource
        
      } catch (error) {
        console.error('发送消息失败:', error)
        this.isAiTyping = false
        this.isStreaming = false
      }
    },
    
    handleAiMessage(data) {
      this.currentAiResponse += data
      this.scrollToBottom()
    },
    
    handleAiError(error) {
      console.error('AI 回复出错:', error)
      this.connectionError = true
      this.finishAiResponse()
      
      // 5秒后自动隐藏错误提示
      setTimeout(() => {
        this.connectionError = false
      }, 5000)
    },
    
    handleAiClose() {
      this.finishAiResponse()
    },
    
    finishAiResponse() {
      this.isStreaming = false
      
      // 如果有AI回复内容，添加到消息列表
      if (this.currentAiResponse.trim()) {
        this.addMessage(this.currentAiResponse, false)
        this.currentAiResponse = ''
        
        // 保存对话历史
        this.saveConversationHistory()
      }
      
      this.isAiTyping = false
      
      // 重置连接错误状态（确保正常结束时清除错误提示）
      this.connectionError = false
      
      // 关闭连接
      if (this.currentEventSource) {
        this.currentEventSource.close()
        this.currentEventSource = null
      }
    },
    
    scrollToBottom() {
      this.$nextTick(() => {
        const container = this.$refs.messagesContainer
        if (container) {
          container.scrollTop = container.scrollHeight
        }
      })
    },
    
    initializeChat() {
      this.memoryId = generateMemoryId()
      console.log('聊天室ID:', this.memoryId)
    },

    goBack() {
      this.$router.go(-1)
    },

    retryConnection() {
      this.connectionError = false
      this.checkLoginStatus()
    },
    
    /**
     * 加载聊天会话列表
     */
    async loadChatSessions() {
      if (!this.isLoggedIn) {
        return
      }
      
      try {
        this.isLoadingSessions = true
        const response = await getChatSessions()
        console.log('会话列表API响应:', response)
        
        if (response.code === 200) {
          this.chatSessions = response.data || []
          console.log('聊天会话列表加载成功:', this.chatSessions)
          
          // 只有在没有选中会话时才自动选择第一个活跃的
          if (this.chatSessions.length > 0 && !this.selectedSessionId) {
            const activeSession = this.chatSessions.find(s => s.status === 'active')
            if (activeSession) {
              await this.selectSession(activeSession)
            }
          } else if (this.chatSessions.length > 0 && this.selectedSessionId) {
            // 若已有选中会话，则同步更新标题为后端最新标题（解决仍显示“新会话”的问题）
            const current = this.chatSessions.find(s => s.sessionId === this.selectedSessionId)
            if (current) {
              this.selectedSessionTitle = current.sessionTitle
            }
          }
        } else {
          console.error('获取会话列表失败:', response.msg)
        }
      } catch (error) {
        console.error('加载会话列表失败:', error)
      } finally {
        this.isLoadingSessions = false
      }
    },
    
    // 选择会话
    async selectSession(session) {
      console.log('选择会话:', session)
      
      // 清空当前消息列表
      this.messages = []
      
      // 设置选中的会话
      this.selectedSessionId = session.sessionId
      this.selectedSessionTitle = session.sessionTitle
      
      // 从数据库重新获取该会话的最新消息
      await this.loadSessionMessages(session.sessionId)
      
      // 滚动到底部
      this.$nextTick(() => {
        this.scrollToBottom()
      })
    },

    // 加载会话消息
    async loadSessionMessages(sessionId) {
      try {
        const response = await getSessionMessages(sessionId)
        if (response.code === 200) {
          // 过滤掉"新会话"等系统消息，只显示真正的用户对话
          const filteredMessages = response.data.filter(msg => {
            // 跳过"新会话"、"新对话"等系统消息
            if (msg.role === 'user' && 
                (msg.content === '新会话' || 
                 msg.content === '新对话' || 
                 msg.content === '新对话')) {
              return false
            }
            return true
          })
          
          // 转换消息格式，确保timestamp是Date类型
          this.messages = filteredMessages.map(msg => ({
            id: msg.messageId || msg.messageOrder,
            content: msg.content,
            isUser: msg.role === 'user',
            timestamp: new Date(msg.createTime), // 确保是Date类型
            messageOrder: msg.messageOrder
          }))
          
          console.log('会话消息加载成功，过滤后消息数量:', this.messages.length)
        } else {
          console.error('加载会话消息失败:', response.msg)
        }
      } catch (error) {
        console.error('加载会话消息出错:', error)
      }
    },

    // 创建新会话
    async createNewSession() {
      try {
        // 清空当前消息和会话选择
        this.messages = []
        this.selectedSessionId = null
        this.selectedSessionTitle = '新会话'
        
        // 创建新会话（传递初始消息，后端为必填；显示层已在加载时过滤）
        const response = await createChatSession('新会话')
        if (response.code === 200) {
          const newSession = response.data
          this.selectedSessionId = newSession.sessionId
          this.selectedSessionTitle = newSession.sessionTitle
          
          console.log('新会话创建成功:', newSession)
          
          // 重新加载会话列表，确保数据是最新的
          await this.loadChatSessions()
          
          // 滚动到底部
          this.$nextTick(() => {
            this.scrollToBottom()
          })
        } else {
          console.error('创建新会话失败:', response.msg)
        }
      } catch (error) {
        console.error('创建新会话出错:', error)
      }
    },
    
    /**
     * 删除会话
     */
    async deleteSession(sessionId) {
      if (!this.isLoggedIn) {
        return
      }
      
      try {
        const response = await deleteChatSession(sessionId)
        if (response.code === 200) {
          // 从列表中移除
          this.chatSessions = this.chatSessions.filter(s => s.sessionId !== sessionId)
          
          // 如果删除的是当前选中的会话，清空消息和选择状态
          if (this.selectedSessionId === sessionId) {
            this.messages = []
            this.selectedSessionId = null
            this.selectedSessionTitle = null
          }
          
          console.log('会话删除成功')
          
          // 重新加载会话列表以确保数据同步
          await this.loadChatSessions()
        } else {
          console.error('删除会话失败:', response.msg)
        }
      } catch (error) {
        console.error('删除会话失败:', error)
      }
    },
    
    /**
     * 清除对话历史
     */
    async clearConversationHistory() {
      if (!this.isLoggedIn) {
        return
      }
      
      try {
        await clearAiTalks()
        this.messages = []
        this.chatSessions = []
        this.selectedSessionId = null
        this.currentSession = null
        console.log('对话历史清除成功')
      } catch (error) {
        console.error('清除对话历史失败:', error)
      }
    },
    
    /**
     * 格式化时间
     */
    formatTime(timestamp) {
      if (!timestamp) return ''
      
      const date = new Date(timestamp)
      const now = new Date()
      const diff = now - date
      
      // 如果是今天
      if (diff < 24 * 60 * 60 * 1000 && date.toDateString() === now.toDateString()) {
        return date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
      }
      
      // 如果是昨天
      const yesterday = new Date(now)
      yesterday.setDate(yesterday.getDate() - 1)
      if (date.toDateString() === yesterday.toDateString()) {
        return '昨天 ' + date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
      }
      
      // 其他日期
      return date.toLocaleDateString('zh-CN', { month: '2-digit', day: '2-digit' })
    },
    
    /**
     * 保存对话历史到后端
     */
    async saveConversationHistory() {
      if (!this.isLoggedIn || this.messages.length === 0) {
        return
      }
      
      try {
        // 转换消息格式为后端需要的格式
        const aiTalkList = this.messages.map(message => ({
          role: message.isUser ? 'user' : 'assistant',
          content: message.content
        }))
        
        await saveAiTalks(aiTalkList)
        console.log('对话历史保存成功')
      } catch (error) {
        console.error('保存对话历史失败:', error)
      }
    }
  },
  
  beforeUnmount() {
    // 组件销毁前关闭连接
    if (this.currentEventSource) {
      this.currentEventSource.close()
    }
  }
}
</script>

<style scoped>
.ai-chat {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #010e50 url(@/assets/images/bg.jpg) center top no-repeat;
  background-size: 100% auto;
  color: #fff;
  overflow: hidden;
}

.chat-header {
  background: rgba(0, 35, 120, 0.8);
  border-bottom: 1px solid rgba(100, 162, 255, 0.3);
  backdrop-filter: blur(10px);
  flex-shrink: 0;
}

.header-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.back-button {
  background: rgba(0, 35, 120, 0.8);
  border: 1px solid rgba(100, 162, 255, 0.6);
  border-radius: 8px;
  color: #fff;
  padding: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  justify-content: center;
}

.back-button:hover {
  background: rgba(2, 88, 240, 0.9);
  transform: translateX(-2px);
}

.title-section {
  flex: 1;
  text-align: center;
  margin: 0 20px;
}

.chat-title {
  font-size: 28px;
  font-weight: bold;
  color: #fff;
  margin: 0;
  text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.3);
  letter-spacing: 2px;
}

.chat-subtitle {
  font-size: 14px;
  color: rgba(255, 255, 255, 0.8);
  margin-top: 5px;
}

.connection-status {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 12px;
  border-radius: 20px;
  font-size: 12px;
  backdrop-filter: blur(5px);
}

.connection-status.connected {
  background: rgba(40, 167, 69, 0.2);
  border: 1px solid rgba(40, 167, 69, 0.4);
  color: #28a745;
}

.connection-status.disconnected {
  background: rgba(220, 53, 69, 0.2);
  border: 1px solid rgba(220, 53, 69, 0.4);
  color: #dc3545;
}

.status-dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  animation: pulse 2s infinite;
}

.connected .status-dot {
  background: #28a745;
}

.disconnected .status-dot {
  background: #dc3545;
}

@keyframes pulse {
  0% { opacity: 1; }
  50% { opacity: 0.5; }
  100% { opacity: 1; }
}

.chat-container {
  flex: 1;
  display: flex;
  overflow: hidden;
}

.chat-sidebar {
  width: 300px;
  background: rgba(0, 35, 120, 0.6);
  border-right: 1px solid rgba(100, 162, 255, 0.3);
  display: flex;
  flex-direction: column;
  backdrop-filter: blur(10px);
}

/* 主聊天区域作为容器以便放置覆盖按钮 */
.main-chat-area {
  position: relative;
}

.floating-delete-btn {
  position: absolute;
  top: 8px;
  right: 8px;
  background: rgba(220, 53, 69, 0.2);
  border: 1px solid rgba(220, 53, 69, 0.5);
  border-radius: 6px;
  color: #fff;
  padding: 6px;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 2;
}

.floating-delete-btn:hover:not([disabled]) {
  background: rgba(220, 53, 69, 0.3);
  border-color: rgba(220, 53, 69, 0.8);
  transform: scale(1.05);
}

.floating-delete-btn[disabled] {
  opacity: 0.5;
  cursor: not-allowed;
}

.sidebar-header {
  padding: 20px;
  border-bottom: 1px solid rgba(100, 162, 255, 0.3);
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: rgba(0, 35, 120, 0.8);
}

.header-actions {
  display: flex;
  gap: 8px;
  align-items: center;
}

/* 清除顶部删除当前会话按钮样式（已移除按钮） */

.new-chat-btn {
  background: rgba(40, 167, 69, 0.2);
  border: 1px solid rgba(40, 167, 69, 0.5);
  border-radius: 6px;
  color: #fff;
  padding: 6px;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  justify-content: center;
}

.new-chat-btn:hover {
  background: rgba(40, 167, 69, 0.3);
  border-color: rgba(40, 167, 69, 0.8);
  transform: scale(1.05);
}

.sidebar-header h3 {
  margin: 0;
  color: #fff;
  font-size: 18px;
  font-weight: 600;
}

.clear-history-btn {
  background: rgba(255, 107, 107, 0.2);
  border: 1px solid rgba(255, 107, 107, 0.5);
  border-radius: 6px;
  color: #fff;
  padding: 6px;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  justify-content: center;
}

.clear-history-btn:hover {
  background: rgba(255, 107, 107, 0.3);
  border-color: rgba(255, 107, 107, 0.8);
  transform: scale(1.05);
}

.history-list {
  flex: 1;
  overflow-y: auto;
  padding: 10px;
}

.no-history {
  text-align: center;
  padding: 40px 20px;
  color: rgba(255, 255, 255, 0.6);
}

.no-history p {
  margin: 0;
  font-size: 14px;
}

.history-item {
  padding: 15px;
  margin-bottom: 10px;
  background: rgba(0, 35, 120, 0.4);
  border: 1px solid rgba(100, 162, 255, 0.2);
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
  backdrop-filter: blur(5px);
  position: relative;
}

.history-item:hover {
  background: rgba(0, 35, 120, 0.6);
  border-color: rgba(100, 162, 255, 0.4);
  transform: translateX(2px);
}

.history-item.active {
  background: rgba(2, 88, 240, 0.6);
  border-color: rgba(100, 162, 255, 0.8);
  box-shadow: 0 0 15px rgba(2, 88, 240, 0.3);
}

.history-content {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.history-question {
  color: #fff;
  font-size: 14px;
  line-height: 1.4;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.session-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 10px;
}

.message-count {
  color: rgba(100, 162, 255, 0.8);
  font-size: 11px;
  background: rgba(100, 162, 255, 0.1);
  padding: 2px 6px;
  border-radius: 10px;
}

.history-time {
  color: rgba(255, 255, 255, 0.6);
  font-size: 12px;
}


.main-chat-area {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.messages-container {
  flex: 1;
  overflow-y: auto;
  padding: 20px 0;
}

.welcome-message {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  padding: 0 20px;
}

.welcome-content {
  text-align: center;
  max-width: 500px;
  color: rgba(255, 255, 255, 0.9);
  background: rgba(0, 35, 120, 0.4);
  padding: 40px;
  border-radius: 20px;
  border: 1px solid rgba(100, 162, 255, 0.3);
  backdrop-filter: blur(10px);
}

.welcome-icon {
  font-size: 64px;
  margin-bottom: 20px;
  filter: drop-shadow(0 4px 8px rgba(0, 0, 0, 0.3));
}

.welcome-content h2 {
  font-size: 24px;
  margin-bottom: 15px;
  color: #fff;
  text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.3);
}

.welcome-content p {
  margin-bottom: 15px;
  line-height: 1.6;
  font-size: 16px;
}

.welcome-content ul {
  text-align: left;
  margin: 20px 0;
  padding-left: 20px;
}

.welcome-content li {
  margin-bottom: 8px;
  line-height: 1.5;
  position: relative;
}

.welcome-content li::before {
  content: "✨";
  position: absolute;
  left: -20px;
}

/* AI 正在回复时的消息样式 */
.chat-message {
  display: flex;
  margin-bottom: 20px;
  padding: 0 20px;
}

.ai-message {
  justify-content: flex-start;
  flex-direction: row;
}

.message-avatar {
  display: flex;
  align-items: flex-start;
  margin: 0 10px;
}

.avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
  font-weight: bold;
  color: white;
  border: 2px solid rgba(100, 162, 255, 0.3);
  backdrop-filter: blur(5px);
}

.ai-avatar {
  background: linear-gradient(135deg, #6c757d, #8a9ba8);
  box-shadow: 0 2px 8px rgba(108, 117, 125, 0.3);
}

.message-content {
  max-width: 70%;
  min-width: 100px;
}

.message-bubble {
  padding: 12px 16px;
  border-radius: 18px;
  position: relative;
  word-wrap: break-word;
  word-break: break-word;
  background: rgba(0, 35, 120, 0.6);
  color: #fff;
  border-bottom-left-radius: 4px;
  backdrop-filter: blur(10px);
  border: 1px solid rgba(100, 162, 255, 0.2);
  box-shadow: 0 4px 12px rgba(0, 35, 120, 0.2);
}

.ai-typing-content {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.ai-response-text {
  font-size: 14px;
  line-height: 1.5;
}

/* AI实时回复的Markdown样式 */
.ai-response-text.message-markdown h1,
.ai-response-text.message-markdown h2,
.ai-response-text.message-markdown h3,
.ai-response-text.message-markdown h4,
.ai-response-text.message-markdown h5,
.ai-response-text.message-markdown h6 {
  margin: 0.5em 0;
  font-weight: bold;
  color: #fff;
}

.ai-response-text.message-markdown h1 { font-size: 1.5em; }
.ai-response-text.message-markdown h2 { font-size: 1.3em; }
.ai-response-text.message-markdown h3 { font-size: 1.2em; }
.ai-response-text.message-markdown h4 { font-size: 1.1em; }
.ai-response-text.message-markdown h5 { font-size: 1em; }
.ai-response-text.message-markdown h6 { font-size: 0.9em; }

.ai-response-text.message-markdown p {
  margin: 0.5em 0;
  color: #fff;
}

.ai-response-text.message-markdown ul,
.ai-response-text.message-markdown ol {
  margin: 0.5em 0;
  padding-left: 1.5em;
  color: #fff;
}

.ai-response-text.message-markdown li {
  margin: 0.2em 0;
}

.ai-response-text.message-markdown code {
  background-color: rgba(255, 255, 255, 0.15);
  padding: 0.2em 0.4em;
  border-radius: 3px;
  font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
  font-size: 0.9em;
  color: #fff;
  border: 1px solid rgba(100, 162, 255, 0.3);
}

.ai-response-text.message-markdown pre {
  background-color: rgba(0, 0, 0, 0.3);
  padding: 1em;
  border-radius: 5px;
  overflow-x: auto;
  margin: 0.5em 0;
  border: 1px solid rgba(100, 162, 255, 0.3);
}

.ai-response-text.message-markdown pre code {
  background-color: transparent;
  padding: 0;
  font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
  font-size: 0.9em;
  border: none;
}

.ai-response-text.message-markdown blockquote {
  border-left: 4px solid rgba(100, 162, 255, 0.6);
  padding-left: 1em;
  margin: 0.5em 0;
  font-style: italic;
  color: rgba(255, 255, 255, 0.8);
  background: rgba(0, 35, 120, 0.3);
  border-radius: 0 4px 4px 0;
}

.ai-response-text.message-markdown a {
  color: #64a2ff;
  text-decoration: underline;
}

.ai-response-text.message-markdown table {
  border-collapse: collapse;
  width: 100%;
  margin: 0.5em 0;
  background: rgba(0, 35, 120, 0.3);
  border-radius: 4px;
  overflow: hidden;
}

.ai-response-text.message-markdown th,
.ai-response-text.message-markdown td {
  border: 1px solid rgba(100, 162, 255, 0.3);
  padding: 0.5em;
  text-align: left;
  color: #fff;
}

.ai-response-text.message-markdown th {
  background: rgba(2, 88, 240, 0.4);
  font-weight: bold;
}

.ai-response-text.message-markdown hr {
  border: none;
  border-top: 1px solid rgba(100, 162, 255, 0.4);
  margin: 1em 0;
}

.connection-error {
  position: fixed;
  top: 20px;
  left: 50%;
  transform: translateX(-50%);
  background: linear-gradient(135deg, #dc3545, #c82333);
  color: white;
  padding: 15px 25px;
  border-radius: 10px;
  z-index: 1000;
  animation: slideDown 0.3s ease-out;
  border: 1px solid rgba(220, 53, 69, 0.6);
  backdrop-filter: blur(10px);
  box-shadow: 0 4px 20px rgba(220, 53, 69, 0.3);
}

.error-content {
  display: flex;
  align-items: center;
  gap: 12px;
}

.error-icon {
  font-size: 18px;
}

.retry-button {
  background: rgba(255, 255, 255, 0.2);
  border: 1px solid rgba(255, 255, 255, 0.3);
  border-radius: 6px;
  color: white;
  padding: 4px 12px;
  font-size: 12px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.retry-button:hover {
  background: rgba(255, 255, 255, 0.3);
}

@keyframes slideDown {
  from {
    transform: translateX(-50%) translateY(-100%);
    opacity: 0;
  }
  to {
    transform: translateX(-50%) translateY(0);
    opacity: 1;
  }
}

/* 滚动条样式 */
.messages-container::-webkit-scrollbar,
.history-list::-webkit-scrollbar {
  width: 8px;
}

.messages-container::-webkit-scrollbar-track,
.history-list::-webkit-scrollbar-track {
  background: rgba(255, 255, 255, 0.1);
  border-radius: 4px;
}

.messages-container::-webkit-scrollbar-thumb,
.history-list::-webkit-scrollbar-thumb {
  background: rgba(100, 162, 255, 0.5);
  border-radius: 4px;
}

.messages-container::-webkit-scrollbar-thumb:hover,
.history-list::-webkit-scrollbar-thumb:hover {
  background: rgba(100, 162, 255, 0.7);
}

@media (max-width: 768px) {
  .header-content {
    padding: 15px;
  }
  
  .chat-title {
    font-size: 22px;
  }
  
  .chat-container {
    flex-direction: column;
  }
  
  .chat-sidebar {
    width: 100%;
    height: 200px;
    border-right: none;
    border-bottom: 1px solid rgba(100, 162, 255, 0.3);
  }
  
  .main-chat-area {
    flex: 1;
  }
  
  .messages-container {
    padding: 15px 0;
  }
  
  .welcome-content {
    padding: 30px 20px;
    margin: 0 10px;
  }
  
  .welcome-icon {
    font-size: 48px;
  }
  
  .welcome-content h2 {
    font-size: 20px;
  }
  
  .message-content {
    max-width: 85%;
  }
  
  .chat-message {
    padding: 0 10px;
  }

  .connection-status {
    display: none;
  }
}
</style>
